package cn.kys.modules.system.service.impl;


import cn.kys.common.utils.FileUtil;
import cn.kys.common.utils.SecurityUtils;
import cn.kys.common.utils.ShpWriter;
import cn.kys.common.utils.Zip;
import cn.kys.modules.security.security.vo.JwtUser;
import cn.kys.modules.system.domain.GeomEntity;
import cn.kys.modules.system.pojo.LayerDto;
import cn.kys.modules.system.pojo.SubtaskGeom;
import cn.kys.modules.system.pojo.SubtaskVo;
import cn.kys.modules.system.repository.ToolsResposity;
import cn.kys.modules.system.service.TaskService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.WKTReader;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class TaskServiceImpl implements TaskService {
    @Value("${file.shpUpdate}")
    private String shpUpdate;
    @Autowired
    private ToolsResposity toolsResposity;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    GridFsTemplate gridFsTemplate;
    private SimpleDateFormat sdf_ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Map addTask(String name, int caseid, String casename, boolean is_public, String lat, String lon) {

        String create_time = sdf_.format(new Date());
        Map returnMap = new HashMap();
        String sql = "SELECT * FROM public.t_task where name = '" + name + "'";
        Map formMap = toolsResposity.exeSql(sql);
        String status = "未开始";
        if (formMap == null) {
            String sql_insert = "INSERT INTO public.t_task(name,caseid,casename,status,is_public,lat,lon,create_time) VALUES ('" + name + "'," + caseid + ",'" + casename + "','" + status + "'," + is_public + ",'" + lat + "','" + lon + "','" + create_time + "');";
            toolsResposity.exeSql(sql_insert);
            returnMap.put("success", true);
        } else {
            returnMap.put("success", false);
            returnMap.put("msg", "任务已经存在");
        }
        return returnMap;

    }

    @Override
    public Map editTaskStatus(String id, String status) {
        Map returnMap = new HashMap();
        //判断是否有子任务（是否是举证任务）

        String sql = "SELECT * FROM public.t_task where id = '" + id + "'";
        Map taskMap = toolsResposity.exeSql(sql);
        boolean is_public = (boolean) taskMap.get("is_public");
        if (is_public) {
            String sql_update = "UPDATE public.t_task SET  status='" +
                    status + "' WHERE id= '" + id + "'";
            toolsResposity.exeSql(sql_update);
            returnMap.put("success", true);
        } else {
            //查看是否有子任务
            String sql_subtask = "SELECT * FROM public.t_subtask where taskid = '" + id + "'";
            List subTaskList = toolsResposity.exeSqlList(sql_subtask);

            if (subTaskList.size() > 0) {
                //有子任务，可以更新主任务
                String sql_update = "UPDATE public.t_task SET  status='" +
                        status + "' WHERE id= '" + id + "'";
                toolsResposity.exeSql(sql_update);
                //子任务的状态都改成已开始
                String sql_update_subtask = "UPDATE public.t_subtask SET  status='" +
                        status + "' WHERE taskid= '" + id + "'";
                toolsResposity.exeSql(sql_update_subtask);
                returnMap.put("success", true);
            } else {
                returnMap.put("success", false);
                returnMap.put("msg", "请分配人员任务！");
            }
        }
        return returnMap;

    }


    public void editSubTaskStatus(String taskid, String status) {
        JwtUser jwtUser = (JwtUser) userDetailsService.loadUserByUsername(SecurityUtils.getUsername());
        Long userid = jwtUser.getId();

        String sql_update = "UPDATE public.t_subtask SET  status='" +
                status + "' WHERE taskid= '" + taskid + "' and userid = " + userid;
        toolsResposity.exeSql(sql_update);

        //更新mongodb中的数据，先根据taskid和userid查询出subtaskid。
        String sql_search = "select id from t_subtask where userid = " + userid + " and taskid = '" + taskid + "'";
        Map mapSubTask = toolsResposity.exeSql(sql_search);
        String subTaskId = mapSubTask.get("id").toString();

        Query query = new Query(Criteria.where("metadata.globle_subtaskid").is(subTaskId).and("metadata.globle_userid").is(userid));
        Update update = new Update();
        update.set("metadata.globle_status", status);
        mongoTemplate.updateMulti(query, update, "tableEntity");


    }



    @Override
    public void addTaskUsers(String _taskid, String userJson) {

        List<Integer> oldList = new ArrayList<>();
        String sql_search = "SELECT * FROM public.t_subtask where taskid = '" + _taskid + "'";
        List list = toolsResposity.exeSqlList(sql_search);
        for (int i = 0; i < list.size(); i++) {
            Map map = (Map) list.get(i);
            int userid = Integer.parseInt(map.get("userid").toString());
            oldList.add(userid);
        }
        String status = "未开始";

        JSONArray jsonArray = JSON.parseArray(userJson);
        String create_time = sdf_.format(new Date());
        List<Integer> newList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject ob = (JSONObject) jsonArray.get(i);
            String username = ob.getString("username");
            String taskname = ob.getString("taskname");
            int userid = Integer.parseInt(ob.getString("userid"));
            int taskid = Integer.parseInt(ob.getString("taskid"));


            newList.add(userid);
        }

        List deleteList = compare(oldList, newList);
        List addList = compare(newList, oldList);


        for (int i = 0; i < deleteList.size(); i++) {
            int deleteUserid = Integer.parseInt(deleteList.get(i).toString());

            String sql_subtask = "SELECT * FROM public.t_subtask where userid = " + deleteUserid + " and taskid = '" + _taskid + "'";
            Map subtaskMap = toolsResposity.exeSql(sql_subtask);
            int subtaskid = Integer.parseInt(subtaskMap.get("id").toString());

            //删除t_subtask
            String sql_delete = "delete from t_subtask where userid = " + deleteUserid + " and taskid = '" + _taskid + "'";
            toolsResposity.exeSql(sql_delete);
            //删除.t_subtask_polygon
            String sql_delete_subtask_polygon = "delete from t_subtask_polygon where subtaskid = " + subtaskid + " and taskid = '" + _taskid + "'";
            toolsResposity.exeSql(sql_delete_subtask_polygon);
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject ob = (JSONObject) jsonArray.get(i);
            String username = ob.getString("username");
            String taskname = ob.getString("taskname");
            int userid = Integer.parseInt(ob.getString("userid"));
            int taskid = Integer.parseInt(ob.getString("taskid"));

            if (addList.contains(userid)) {
                //添加
                String sql = "SELECT * FROM public.t_subtask where userid = '" + userid + "' and taskid = '" + taskid + "'";
                Map map = toolsResposity.exeSql(sql);
                if (map == null) {
                    String sql_insert = "INSERT INTO public.t_subtask(taskid,taskname,userid,username,status,create_time) VALUES (" + taskid + ",'" + taskname + "'," + userid + ",'" + username + "','" + status + "','" + create_time + "');";
                    toolsResposity.exeSql(sql_insert);
                }
            }

        }

    }

    // 1、2、3 和 1、2、4     先找出3 再找到4
    public List compare(List<Integer> oldList, List<Integer> newList) {
        List resultList = new ArrayList();
        for (int i = 0; i < oldList.size(); i++) {
            int oldI = oldList.get(i);
            if (!newList.contains(oldI)) {
                resultList.add(oldI);
            }
        }
        return resultList;
    }

    @Override
    public List getAllTasks() {

        String sql = "SELECT * FROM public.t_task";
        List<Map> listTask = toolsResposity.exeSqlList(sql);

        for (Map mapTask : listTask) {
            Integer idTask = (Integer.parseInt(mapTask.get("id") + ""));//任务id
            String sql2 = String.format("SELECT * from t_subtask where taskid=%d", idTask);
            List<Map> listSubTask = toolsResposity.exeSqlList(sql2);
            Integer subTaskSum = 0;
            Integer subTaskFinishSum = 0;

            for (Map mapSubTask : listSubTask) {
                Integer subtaskid = (Integer.parseInt(mapSubTask.get("id") + ""));//子任务id
                //表t_subtask_geom中所有subtaskid=186 这个子任务的所有 数量
                Map<String, Integer> mapSubTaskCount = toolsResposity.exeSql(String.format("select count(*) from  t_subtask_geom where subtaskid=%d", subtaskid));
                subTaskSum = +Integer.parseInt(mapSubTaskCount.get("count") + "");
                //monggoDB中所有subtaskid=186 这个子任务的所有 数量
                Query query = new Query(Criteria.where("metadata.globle_subtaskid").is(subtaskid + "").and("metadata.globle_status").is("审核通过"));

                Long hasFinished = mongoTemplate.count(query, JSONObject.class, "tableEntity");

                subTaskFinishSum += Integer.parseInt(hasFinished + "");
//
            }

            mapTask.put("subTaskSum", subTaskSum);
            mapTask.put("subTaskFinishSum", subTaskFinishSum);
            mapTask.put("subTaskUnFinishSum", subTaskSum - subTaskFinishSum);
        }


        return listTask;



    }

    @Override
    public List getFinishAndUnFinishTaskNum() {
        return null;
    }

    @Override
    public List getTasksByParam(boolean is_public) {

        // and status != '未开始'
        String sql = "SELECT * FROM public.t_task where is_public = " + is_public + " and status != '已结束' order by create_time desc";
        return toolsResposity.exeSqlList(sql);
    }

    @Override
    public void editPolygonStatus(String subtaskPolygonId, String status) {

    }


    @Override
    public void bingindgPolygonMongodb(String taskid, String subTask) {
        /*JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(SecurityUtils.getUsername());
        Long userid = jwtUser.getId();*/

        String sql = "SELECT layername FROM public.t_case_editlayer where caseid in (select caseid from t_task where id = '" + taskid + "')";
        Map map = toolsResposity.exeSql(sql);
        String layername = map.get("layername").toString();
        //解析subTask json字符串
        JSONArray jsonArray = JSON.parseArray(subTask);

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject ob = (JSONObject) jsonArray.get(i);
            String subtaskid = ob.getString("id");
            String polygons = ob.getString("polygon");

            //先删除，再添加
            String sql_delete = "delete from t_subtask_polygon where subtaskid in (" + subtaskid + ")";
            toolsResposity.exeSql(sql_delete);

            String poly[] = polygons.split("@");
            for (int j = 0; j < poly.length; j++) {
                String tempPoly = poly[j];
                String sql_insert = "INSERT INTO public.t_subtask_polygon(subtaskid,polygon) VALUES (" + subtaskid + ",'" + tempPoly + "');";
                toolsResposity.exeSql(sql_insert);

                //polygon跟图层相交判断，找到需要编辑的图形，插入到mongodb数据库中。
                String sql_geom = "SELECT gid,jsonb_build_object(\n" +
                        "    'type',       'Feature',\n" +
                        "    'gid',         gid,\n" +
                        "    'geometry',   ST_AsGeoJSON(geom)::jsonb,\n" +
                        "    'properties', to_jsonb(row) - 'gid' - 'geom'\n" +
                        ") FROM (SELECT * FROM " + layername + ") row limit 10;";
                List listGeoJson = toolsResposity.exeSqlList(sql_geom);
                for (int k = 0; k < listGeoJson.size(); k++) {
                    Map geoJsonMap = (Map) listGeoJson.get(k);
                    int gid = Integer.parseInt(geoJsonMap.get("gid").toString());
                    String geojson = geoJsonMap.get("jsonb_build_object").toString();
                    GeomEntity geomEntity = new GeomEntity();
                    geomEntity.setCreated(false);
                    geomEntity.setLayername(layername);
                    geomEntity.setGid(gid);
                    geomEntity.setSubtaskid(Integer.parseInt(subtaskid));
                    geomEntity.setGeojson(geojson);
                    mongoTemplate.save(geomEntity);
                }
            }


        }


    }


    @Override
    public void bingindgPolygonPG(String taskid, String subTask) {

        String sql = "SELECT layername FROM public.t_case_editlayer where caseid in (select caseid from t_task where id = '" + taskid + "')";
        Map map = toolsResposity.exeSql(sql);
        String layername = map.get("layername").toString();
        //解析subTask json字符串

        JSONObject ob = (JSONObject) JSONObject.parse(subTask);


        String subtaskid = ob.getString("id");
        String polygons = ob.getString("polygon");

        //先删除，再添加
        String sql_delete = "delete from t_subtask_polygon where subtaskid in (" + subtaskid + ")";
        toolsResposity.exeSql(sql_delete);

        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
        WKTReader reader = new WKTReader(geometryFactory);

        if (!"".equals(polygons)) {
            String poly[] = polygons.split("@");
            GeometryFactory gf = new GeometryFactory();
            Polygon[] polys = new Polygon[poly.length];
            for (int j = 0; j < poly.length; j++) {
                try {
                    String tempPoly = "POLYGON((" + poly[j] + "))";
                    Polygon p = (Polygon) reader.read(tempPoly);
                    polys[j] = p;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            MultiPolygon mPoly = gf.createMultiPolygon(polys);
            String polygon_text = "st_geomfromtext('" + mPoly.toString() + "'" + ",4326)";

            String sql_insert = "INSERT INTO public.t_subtask_polygon(subtaskid,taskid,polygon,geom) VALUES (" + subtaskid + "," + taskid + ",'" + mPoly.toString() + "'," + polygon_text + ");";
            toolsResposity.exeSql(sql_insert);

            //删除待编辑的图斑
            String sql_subtask_geom = "delete from t_subtask_geom where subtaskid in (" + subtaskid + ")";
            toolsResposity.exeSql(sql_subtask_geom);

            String sql_intersects = "select id,ST_AsText(geom) from " + layername + " where ST_Intersects(" + polygon_text + ",geom)";
            List listGeoJson = toolsResposity.exeSqlList(sql_intersects);
            for (int k = 0; k < listGeoJson.size(); k++) {
                Map geoJsonMap = (Map) listGeoJson.get(k);
                int gid = Integer.parseInt(geoJsonMap.get("id").toString());
                String st_astext = geoJsonMap.get("st_astext").toString();

                String geom_text = "st_geomfromtext('" + st_astext + "'" + ",4490)";
                String sql_insert_geom = "INSERT INTO public.t_subtask_geom(subtaskid,taskid,gid,layername,iscreated,geom) VALUES (" + subtaskid + "," + taskid + "," + gid + ",'" + layername + "'," + false + "," + geom_text + ");";
                toolsResposity.exeSql(sql_insert_geom);
            }
        }


    }

    @Override
    public Map judgeBingdingPolygon(String taskid, String subTask) {
        String sql = "SELECT layername FROM public.t_case_editlayer where caseid in (select caseid from t_task where id = '" + taskid + "')";
        Map map = toolsResposity.exeSql(sql);
        String layername = map.get("layername").toString();

        Map returnMap = new HashMap();
        /**
         * 1、同一个人的图斑，先组织成一个MultiPolygon，再跟t_subtask_polygon表中内容比较 同一个任务，不能相交
         * 2、判断最新相交的edit图斑，是否跟已有图斑 t_subtask_geom 的主键gid有相同的，如果有返回。
         */

        JSONObject ob = (JSONObject) JSONObject.parse(subTask);
        String subtaskid = ob.getString("id");
        String polygons = ob.getString("polygon");


        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
        WKTReader reader = new WKTReader(geometryFactory);
        String poly[] = polygons.split("@");
        GeometryFactory gf = new GeometryFactory();
        Polygon[] polys = new Polygon[poly.length];
        for (int j = 0; j < poly.length; j++) {
            try {
                String tempPoly = "POLYGON((" + poly[j] + "))";
                Polygon p = (Polygon) reader.read(tempPoly);
                polys[j] = p;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        MultiPolygon mPoly = gf.createMultiPolygon(polys);
        String polygon_text = "st_geomfromtext('" + mPoly.toString() + "'" + ",4326)";

        //查询数量
        String sql_subtask_polygon_count = "select count(*) from " + layername + " where ST_Intersects(" + polygon_text + ",geom)";
        Map countMap = toolsResposity.exeSql(sql_subtask_polygon_count);
        int count = Integer.parseInt(countMap.get("count").toString());
        if (count < 1000) {
            String sql_subtask_polygon = "select * from t_subtask_polygon where ST_Intersects(" + polygon_text + ",geom) and subtaskid != '" + subtaskid + "' and taskid = '" + taskid + "'";

            List subTaskPolygonList = toolsResposity.exeSqlList(sql_subtask_polygon);

            if (subTaskPolygonList.size() != 0) {
                returnMap.put("isExtentCross", true);
                returnMap.put("isExtentCrossMsg", "新提交的范围与其他人的任务范围有交集，请重新绘制！");
            } else {
                returnMap.put("isExtentCross", false);

                //新的范围，与子任务表相交出来的图斑gid
                String sql_intersects = "select id from " + layername + " where ST_Intersects(" + polygon_text + ",geom)";
                List gidList = toolsResposity.exeSqlList(sql_intersects);

                String sql_subtask_geom = "select gid from t_subtask_geom where taskid = " + taskid + "and subtaskid != " + subtaskid;
                List subTaskGeomList = toolsResposity.exeSqlList(sql_subtask_geom);

                //相交的个数
                int repetition = getRepetition(gidList, subTaskGeomList);
                if (repetition == 0) {//没有相交
                    returnMap.put("isEditGeomCross", false);

                } else {
                    //相交
                    returnMap.put("isEditGeomCross", true);
                    returnMap.put("isEditGeomCrossMsg", "新提交的编辑图斑与其他人的编辑图斑有重合（" + repetition + "个），请重新绘制！");
                }
            }
            returnMap.put("over", false);
            returnMap.put("count", count);
        } else {
            returnMap.put("over", true);
            returnMap.put("count", count);
        }


        return returnMap;
    }

    @Override
    public Map getMVTByPerson(String subtaskid, String tileName, int x, int y, int z) {
        String layername = "t_subtask_geom";

        String sql_mvt = "WITH mvtgeom AS ("
                + "SELECT "
                + "ST_AsMVTGeom("
                + "ST_Transform(geom, 3857),"
                + "ST_TileEnvelope(" + z + "," + x + "," + y + ")"
                + ") as geom "
                + "from " + layername + " where subtaskid = " + subtaskid
                + ")SELECT ST_AsMVT(mvtgeom.*, '" + tileName + "') as mvt from mvtgeom";
        return toolsResposity.exeSql(sql_mvt);
    }

    @Override
    public Map getMVTByLayerName(String layername, String tileName, int x, int y, int z) {

        String sql_mvt = "WITH mvtgeom AS ("
                + "SELECT "
                + "ST_AsMVTGeom("
                + "ST_Transform(geom, 3857),"
                + "ST_TileEnvelope(" + z + "," + x + "," + y + ")"
                + ") as geom "
                + "from " + layername
                + ")SELECT ST_AsMVT(mvtgeom.*, '" + tileName + "') as mvt from mvtgeom";
        return toolsResposity.exeSql(sql_mvt);
    }

    @Override
    public Map getMVTByTask(String taskid, String tileName, int x, int y, int z) {

        String layername = "t_subtask_geom";

        String sql_mvt = "WITH mvtgeom AS ("
                + "SELECT "
                + "ST_AsMVTGeom("
                + "ST_Transform(geom, 3857),"
                + "ST_TileEnvelope(" + z + "," + x + "," + y + ")"
                + ") as geom "
                + "from " + layername + " where taskid = " + taskid
                + ")SELECT ST_AsMVT(mvtgeom.*, '" + tileName + "') as mvt from mvtgeom";
        return toolsResposity.exeSql(sql_mvt);
    }

    @Override
    public Map getMVTByGrid(String tileName, int x, int y, int z, String maxLat, String minLat, String maxLon, String minLon, String metre) {
        double degress = 0.000009;//一米等于多少经纬度

        double dmaxLat = Double.parseDouble(maxLat);
        double dminLat = Double.parseDouble(minLat);
        double dmaxLon = Double.parseDouble(maxLon);
        double dminLon = Double.parseDouble(minLon);

        double distanceLat = dmaxLat - dminLat;
        double distanceLon = dmaxLon - dminLon;


        int width = 10;
        int height = 6;
        double size = distanceLon / width;

        //String sql = "SELECT(ST_PixelAsPolygons (ST_AddBand (ST_SetSRID(ST_MakeEmptyRaster( 50, 30, "+dminLon+", "+dmaxLat+", 0.01),4490),'8BSI' :: TEXT,1,0),1,FALSE)).geom";

        String sql = "SELECT(ST_PixelAsPolygons (ST_AddBand (ST_SetSRID(ST_MakeEmptyRaster( " + width + ", " + height + ", " + dminLon + ", " + dmaxLat + ", " + size + "),4490),'8BSI' :: TEXT,1,0),1,FALSE)).geom";

        String sql_mvt = "WITH mvtgeom AS ("
                + "SELECT "
                + "ST_AsMVTGeom("
                + "ST_Transform(geom, 3857),"
                + "ST_TileEnvelope(" + z + "," + x + "," + y + ")"
                + ") as geom "
                + "from (" + sql + ") as geom"
                + ")SELECT ST_AsMVT(mvtgeom.*, '" + tileName + "') as mvt from mvtgeom";
        return toolsResposity.exeSql(sql_mvt);
    }

    //返回相交图斑数量
    public int getRepetition(List listA, List listB) {
        List list1 = new ArrayList();
        List list2 = new ArrayList();

        for (int i = 0; i < listA.size(); i++) {
            Map map = (Map) listA.get(i);
            int gid = Integer.parseInt(map.get("id").toString());
            list1.add(gid);
        }

        for (int i = 0; i < listB.size(); i++) {
            Map map = (Map) listB.get(i);
            try {
                int gid = Integer.parseInt(map.get("gid").toString());
                list2.add(gid);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        List result = new ArrayList();
        for (int i = 0; i < list1.size(); i++) {//遍历list1
            int list1Val = (Integer) list1.get(i);
            if (list2.contains(list1Val)) {//如果存在这个数
                result.add(list1Val);//放进一个list里面，这个list就是交集
            }
        }
        return result.size();
    }

    @Override
    public List getUsers(String roleStr) {
        List list = new ArrayList();
        //String sql = "SELECT * FROM public.users_roles where role_id in (SELECT id FROM public.role where permission = 'cjy')";
        String sql = "SELECT * FROM public.users_roles where role_id in (SELECT id FROM public.role where permission = '" + roleStr + "')";
        List userRoleList = toolsResposity.exeSqlList(sql);
        for (int i = 0; i < userRoleList.size(); i++) {
            Map userRoleMap = (Map) userRoleList.get(i);
            int user_id = Integer.parseInt(userRoleMap.get("user_id").toString());
            String sql_user = "select * from tuser where id = " + user_id;
            Map userMap = toolsResposity.exeSql(sql_user);
            list.add(userMap);
        }
        return list;
    }

    @Override
    public List getUsersByTaskId(String taskid) {
        String sql = "SELECT * FROM public.t_subtask where taskid = '" + taskid + "'";
        List list = toolsResposity.exeSqlList(sql);

        List returnList = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Map subTaskMap = (Map) list.get(i);
            String subtaskid = subTaskMap.get("id").toString();
            String polygonSql = "SELECT * FROM public.t_subtask_polygon where subtaskid = '" + subtaskid + "'";
            List listExtent = toolsResposity.exeSqlList(polygonSql);
            filterMultiPolygon(listExtent);
            subTaskMap.put("extent", listExtent);
            returnList.add(subTaskMap);
        }
        return returnList;
    }

    @Override
    public List<SubtaskVo> getUsersByTaskIdPc(Integer taskid) {
        return null;
    }

    @Override
    public Map editTaskContent(String id, String name, int caseid, String casename, boolean is_public, String lat, String lon) {
     return null;
    }

    @Override
    public void delTaskByIds(String ids) {

        String idArr[] = ids.split(",");
        for (int j = 0; j < idArr.length; j++) {
            String id = idArr[j];
            //删除t_subtask_polygon表中的数据
            String sql_subtask_polygon = "delete from t_subtask_polygon where subtaskid in (select id from t_subtask where taskid ='" + id + "')";
            toolsResposity.exeSql(sql_subtask_polygon);
            //删除t_subtask_geom表中的数据
            String sql_t_subtask_geom = "delete from t_subtask_geom where subtaskid in (select id from t_subtask where taskid ='" + id + "')";
            toolsResposity.exeSql(sql_t_subtask_geom);
            //删除mongodb表中的数据
            //删除mongodb表中的编辑图斑
            String sql = "select id from t_subtask where taskid ='" + id + "'";
            List list = toolsResposity.exeSqlList(sql);
            /*for(int i=0;i<list.size();i++){
                Map map = (Map)list.get(i);
                int subtaskid = Integer.parseInt(map.get("id").toString());
                Query query = new Query(Criteria.where("id").is(subtaskid));
                mongoTemplate.findAndRemove(query, GeomEntity.class,"geomEntity");
            }*/
            //删除mongodb表中的table内容
            for (int i = 0; i < list.size(); i++) {
                Map map = (Map) list.get(i);
                String subtaskid = map.get("id").toString();
                Query query = new Query(Criteria.where("metadata.globle_subtaskid").is(subtaskid));
                mongoTemplate.findAndRemove(query, JSONObject.class, "tableEntity");
            }

            //删除图片
            for (int i = 0; i < list.size(); i++) {
                Map map = (Map) list.get(i);
                String subtaskid = map.get("id").toString();

                Criteria criteriaFile = Criteria.where("metadata.globle_subtaskid").is(subtaskid);

                Query query = new Query(criteriaFile);
                gridFsTemplate.delete(query);
            }

            //删除t_subtask表中的数据
            String sql_subtask = "delete from t_subtask where taskid ='" + id + "'";
            toolsResposity.exeSql(sql_subtask);

            //删除t_task表中的数据
            String sql_task = "delete from t_task where id ='" + id + "'";
            toolsResposity.exeSql(sql_task);
        }

    }

    @Override
    public Map findFormContentByCaseId(String subtaskid, String edit_geoid, String caseid) {
        JwtUser jwtUser = (JwtUser) userDetailsService.loadUserByUsername(SecurityUtils.getUsername());
        Long userid = jwtUser.getId();

        Map returnMap = new HashMap();
        //结构
        String sql = "select * from t_form_content where formid in (SELECT formid FROM public.t_case_form where caseid = '" + caseid + "')";
        List structList = toolsResposity.exeSqlList(sql);
        returnMap.put("struct", structList);

        //内容

        Criteria criteria = Criteria.where("metadata.globle_subtaskid").is(subtaskid);
        criteria.and("metadata.globle_edit_geoid").is(edit_geoid);
        criteria.and("metadata.globle_userid").is(userid);
        Query query = new Query(criteria);
        List contentList = mongoTemplate.find(query, JSONObject.class, "tableEntity");
        if (contentList.size() == 0) {
            returnMap.put("hasContent", false);
        } else {
            returnMap.put("hasContent", true);
        }
        returnMap.put("content", contentList);
        return returnMap;
    }

    @Override
    public Map findGeomByPos(String taskid, String subtaskid, String lon, String lat) {

        JwtUser jwtUser = (JwtUser) userDetailsService.loadUserByUsername(SecurityUtils.getUsername());
        Long userid = jwtUser.getId();

        String sql = "select * from t_case_editlayer where caseid in (SELECT caseid FROM public.t_task where id = " + taskid + ")";
        Map mapLayerName = toolsResposity.exeSql(sql);

        //String layername = mapLayerName.get("layername").toString();
        String layername = "t_subtask_geom";
        String sql_geom = "select *,st_astext(ST_Transform(t.geom,4490))  from " + layername + " t where ST_Contains(ST_Transform(t.geom,4490),ST_PointFromText('POINT(" + lon + " " + lat + ")',4490))";

        Map map = toolsResposity.exeSql(sql_geom);
        if (map == null) {
            Map returnMap = new HashMap();
            returnMap.put("success", false);
            return returnMap;
//            return new ArrayList();
        } else {
            String edit_geoid = map.get("id").toString();
            Criteria criteria = Criteria.where("metadata.globle_subtaskid").is(subtaskid);
            criteria.and("metadata.globle_edit_geoid").is(edit_geoid + "");
            criteria.and("metadata.globle_userid").is(Integer.parseInt(userid + ""));
            Query query1 = new Query(criteria);
            JSONObject jsonObject = mongoTemplate.findOne(query1, JSONObject.class, "tableEntity");
            if (jsonObject != null) {
                System.out.println(jsonObject.toJSONString());
            }
            map.put("table", jsonObject);
            map.put("success", true);
            return filterMap(map);
        }
//        return  new ArrayList();
    }

    @Override
    public void exportShpPolygon(HttpServletRequest request, HttpServletResponse response, String subtaskid) {
        String sql = "select * from t_gps where subtaskid = '" + subtaskid + "' ORDER BY id ASC";
        List list = toolsResposity.exeSqlList(sql);
        Long startTs = System.currentTimeMillis();
        String shpName = startTs + ".shp";
        String shpFile = shpUpdate;
        ShpWriter.WriteVectorFile(list, shpFile + shpName);
        //压缩
        try {
            //遍历shp 压缩
            File file = new File(shpFile);        //获取其file对象
            File[] fs = file.listFiles();    //遍历path下的文件和目录，放在File数组中
            List<String> sourceFilePaths = new ArrayList<String>();
            for (File f : fs) {                    //遍历File[]数组
                if (f.getPath().contains(startTs + "")) {
                    sourceFilePaths.add(f.getAbsolutePath());
                }
            }
            String zipName = startTs + ".zip";
            String zipTempFilePath = shpFile + zipName;
            //调用压缩
            int s = Zip.compress(sourceFilePaths, zipTempFilePath, false);
            System.out.println("成功压缩" + s + "个文件");

            //上传
            File upFile = new File(zipTempFilePath);
            FileUtil.downloadFileAndDelete(request, response, upFile, true);

            //删除shp数据
            for (File f : fs) {                    //遍历File[]数组
                if (f.getPath().contains(startTs + "")) {

                    File tempFile = new File(f.getAbsolutePath());
                    tempFile.delete();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public List list() {
        return null;
    }

    @Override
    public List listCondition(String name, String canme, boolean isPublic) {
        return null;
    }

    @Override
    public Long countUncommit(Integer taskid) {
        return null;
    }

    @Override
    public List<Map> showPolygonList(SubtaskGeom subtaskGeom) {
        return null;
    }

    @Override
    public List<Integer> assignUnboundPolygon(LayerDto layerDto) {
        return null;
    }

    private void filterMultiPolygon(List list) {

        for (int i = 0; i < list.size(); i++) {
            Map map = (Map) list.get(i);
            String multiPolygon = map.get("polygon").toString();

            String st_astext = multiPolygon;

            List listPolygon = new ArrayList();

            if (st_astext.contains("MULTIPOLYGON")) {
                st_astext = st_astext.substring(16, st_astext.length() - 3);
            } else {
                st_astext = st_astext.substring(9, st_astext.length() - 2);
            }

            String[] polygons = st_astext.split("\\)\\), \\(\\(");

            for (int j = 0; j < polygons.length; j++) {
                String polygon = polygons[j].trim();
                if (polygon.contains("),(")) {
                    String[] polygonHole = polygon.split("\\),\\(");
                    listPolygon.add(polygonHole);
                } else {
                    listPolygon.add(polygon);
                }
            }

            map.put("geo", listPolygon);
        }


    }

    private Map filterMap(Map returnMap) {

        String st_astext = returnMap.get("st_astext").toString();

        List listPolygon = new ArrayList();

        if (st_astext.contains("MULTIPOLYGON")) {
            st_astext = st_astext.substring(15, st_astext.length() - 3);
        } else {
            st_astext = st_astext.substring(9, st_astext.length() - 2);
        }

        String[] polygons = st_astext.split("\\)\\), \\(\\(");

        for (int j = 0; j < polygons.length; j++) {
            String polygon = polygons[j].trim();
            if (polygon.contains("),(")) {
                String[] polygonHole = polygon.split("\\),\\(");
                listPolygon.add(polygonHole);
            } else {
                listPolygon.add(polygon);
            }
        }
        returnMap.put("geo", listPolygon);
        return returnMap;
    }
}

